package com.myblog.aspect;


import com.alibaba.fastjson.JSON;
import com.myblog.annotation.Log;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogAspect {


    //确定切点
    @Pointcut("@annotation(com.myblog.annotation.Log)")
    public void pointCut(){

    }
    //在切点的增强方法
    @Around("pointCut()")
    public Object pointLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object ret=null;
        try{
            handleBefore(proceedingJoinPoint);
            ret = proceedingJoinPoint.proceed();
            handeleAfter(ret);
        }
        finally {
            log.info("=======End=======" + System.lineSeparator());
        }
        return ret;

    }

    private void handeleAfter(Object ret) {
        log.info("Response       : {}",JSON.toJSONString(ret));
    }

    public void handleBefore(ProceedingJoinPoint proceedingJoinPoint){
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=  servletRequestAttributes.getRequest();
        //获取被增强方法上的注解对象
        Log sysLog=getSysLog(proceedingJoinPoint);
        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName   : {}", sysLog.BusinessName());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",proceedingJoinPoint.getSignature().getDeclaringTypeName(),((MethodSignature)proceedingJoinPoint.getSignature()).getName() );
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(proceedingJoinPoint.getArgs()));
    }

    private Log getSysLog(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        return methodSignature.getMethod().getAnnotation(Log.class);
    }


}
